package com.tengits.upgrade;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

@TargetApi(Build.VERSION_CODES.CUPCAKE)
public class VersionUpdateAsyncTask extends AsyncTask<String, Long, String> {

    // 最新的版本号
    private ProgressDialog progressDialog;
    private int contentLength;
    private Context context;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public VersionUpdateAsyncTask(Context context) {
        this.context = context;
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.setCancelable(false);
        progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (getStatus() == Status.RUNNING) {
                    cancel(true);
                }
            }
        });
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请耐心等待...");
        progressDialog.setProgressNumberFormat(null);
        progressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Long... values) {
        super.onProgressUpdate(values);

        progressDialog.setMax(contentLength);
        progressDialog.setProgress(values[0].intValue());
    }

    @Override
    protected String doInBackground(String... params) {
        String urlDownLoader = params[0];
        String dirName = urlDownLoader.split("/")[urlDownLoader.split("/").length - 1];


        // String localURL = EasySharedPreference.getSharedStringData(PrefsConst.VERSION_LOCAL_ADDRESS);
        // if (localURL.contains(dirName)) {
        // 	installNewVersion(localURL);
        // 	return "";
        // }


        // String verCode = params[1];
        try {
            URL url = new URL(urlDownLoader);
            // 打开连接
            URLConnection con = url.openConnection();
            con.setDoInput(true);
            con.connect();
            // 通过连接获得输入流
            InputStream in = con.getInputStream();
            // 通过连接获得文件的长度
            contentLength = con.getContentLength();
            // 定义一个存储卡名

            FileOutputStream fs = new FileOutputStream(
                    PathUtils.appDownLoadPath(context) + dirName);
            byte[] buffer = new byte[1024];
            long bytesum = 0;
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
                publishProgress(bytesum);
            }
            in.close();
            fs.close();
            return PathUtils.appDownLoadPath(context) + dirName;

        } catch (Exception e) {
            Log.e("upgrade", e.getMessage());
            e.printStackTrace();
        }

        return "";
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (progressDialog.isShowing())
            progressDialog.dismiss();
        if (!TextUtils.isEmpty(result)) {
            installNewVersion(result);
        }
    }

    // 下载完成之后安装
    private void installNewVersion(String downLoaderpath) {
        if (TextUtils.isEmpty(downLoaderpath)) {
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("path", PathUtils.appDownLoadPath(context)
                + downLoaderpath.split("/")[downLoaderpath
                .split("/").length - 1]);
        intent.setAction("download_apk_broadcast");
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }
}
